<template>
  <!--  <a-button-->
  <!--    class="editable-add-btn"-->
  <!--    style="margin-bottom: 8px"-->
  <!--    @click="handleAdd"-->
  <!--    >Add</a-button-->
  <!--  >-->
  <!-- todo 这里需要嵌套一个表单用于新增 -->
  <div>
    <a-button type="primary" @click="showModal">Add</a-button>
    <a-modal v-model:open="open" title="Title" :confirm-loading="confirmLoading" @ok="handleOk">
      <!--      <p>{{ modalText }}</p>-->
      <a-form
          :model="formState"
          name="basic"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 16 }"
          autocomplete="off"
          @finish="onFinish"
          @finishFailed="onFinishFailed"
      >
        <!--todo 这里name 和formState需要修改-->
        <a-form-item
            label="姓名"
            name="name"
            :rules="[{ required: true, message: '请输入姓名！' }]"
        >
          <a-input v-model:value="formState.name"/>
        </a-form-item>
        <a-form-item
            label="账号"
            name="uname"
            :rules="[{ required: true, message: '请输入账户！' }]"
        >
          <a-input v-model:value="formState.uname"/>
        </a-form-item>

        <a-form-item
            label="密码"
            name="pwd"
            :rules="[{ required: true, message: '请输入密码！' }]"
        >
          <a-input-password v-model:value="formState.pwd"/>
        </a-form-item>
        <a-form-item
            label="性别"
            name="sex"
            :rules="[{ required: true, message: '请选择性别！' }]"
        >
          <div>
            <a-radio-group v-model:value="formState.sex">
              <a-radio-button value="1">男</a-radio-button>
              <a-radio-button value="2">女</a-radio-button>
            </a-radio-group>
          </div>
        </a-form-item>
        <a-form-item
            label="年龄"
            name="age"
            :rules="[{ required: true, message: '请输入年龄！' }]"
        >
          <a-input-number id="inputNumber" v-model:value="formState.age" :defaultValue="1" :min="1" :max="130"/>
        </a-form-item>
        <a-form-item
            label="用户权限"
            name="utype"
            :rules="[{ required: true, message: '请选择用户权限！' }]"
        >
          <div>
            <a-radio-group v-model:value="formState.utype">
              <a-radio-button value="ROLE_1">管理员</a-radio-button>
              <a-radio-button value="ROLE_2">医生</a-radio-button>
            </a-radio-group>
          </div>
        </a-form-item>
        <a-form-item
            label="医师级别"
            name="levelId"
            :rules="[{ required: true, message: '请选择医师级别！' }]"
        >
          <div>
            <a-radio-group v-model:value="formState.levelId">
              <a-radio-button value="1">主任医师</a-radio-button>
              <a-radio-button value="2">普通医师</a-radio-button>
              <a-radio-button value="3">实习医师</a-radio-button>
            </a-radio-group>
          </div>
        </a-form-item>
        <a-form-item
            label="诊治类别"
            name="typeId"
            :rules="[{ required: true, message: '请选择诊治类别！' }]"
        >
          <div>
            <a-radio-group v-model:value="formState.typeId">
              <a-radio-button value="1">肩部</a-radio-button>
              <a-radio-button value="2">踝部</a-radio-button>
              <a-radio-button value="3">膝部</a-radio-button>
              <a-radio-button value="9">腰部</a-radio-button>
              <a-radio-button value="10">头部</a-radio-button>
              <a-radio-button value="11">肘部</a-radio-button>
              <a-radio-button value="12">腿部</a-radio-button>
            </a-radio-group>
          </div>
        </a-form-item>
        <a-form-item
            label="电话"
            name="phone"
            :rules="[{ required: true, message: '请输入电话！' }]"
        >
          <a-input v-model:value="formState.phone"/>
        </a-form-item>
        <a-form-item
            label="医院"
            name="hospital"
            :rules="[{ required: true, message: '请输入医院！' }]"
        >
          <a-input v-model:value="formState.hospital"/>
        </a-form-item>

        <!--        <a-form-item :wrapper-col="{ offset: 8, span: 16 }">-->
        <!--          <a-button type="primary" html-type="submit">Submit</a-button>-->
        <!--        </a-form-item>-->
      </a-form>
    </a-modal>
  </div>
  <!--todo 改成动态加载数据-->
  <a-table :columns="columns" :data-source="dataSource" bordered>
    <template #bodyCell="{ column, text, record }">
      <template
          v-if="
          ['name', 'age', 'sex', 'doctorLevel', 'phone', 'threatType','hospital'].includes(
            column.dataIndex
          )
        "
      >
        <div>
          <a-input
              v-if="editableData[record.key]"
              v-model:value="editableData[record.key][column.dataIndex]"
              style="margin: -5px 0"
          />
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>
      <template v-else-if="column.dataIndex === 'operation'">
        <div class="editable-row-operations">
          <span v-if="editableData[record.key]">
            <a-typography-link @click="save(record.key)"
            >Save</a-typography-link
            >
            <a-popconfirm title="Sure to cancel?" @confirm="cancel(record.key)">
              <a>Cancel</a>
            </a-popconfirm>
          </span>
          <span v-else>
            <a @click="edit(record.key)">Edit</a>
          </span>
          <a-popconfirm
              v-if="dataSource.length"
              title="Sure to delete?"
              @confirm="onDelete(record.key)"
          >
            <a>Delete</a>
          </a-popconfirm>
        </div>
      </template>
    </template>
  </a-table>
</template>
<script setup>
import {cloneDeep} from "lodash-es";
import {onMounted, reactive, ref} from "vue";
import myAxios from "../plugins/myAxios.js";

const columns = [
  {
    title: "医生姓名",
    dataIndex: "name",
    // width: "25%",
  },
  {
    title: "年龄",
    dataIndex: "age",
    // width: "15%",
  },
  {
    title: "性别",
    dataIndex: "sex",
  },
  {
    title: "级别",
    dataIndex: "doctorLevel",
  },
  {
    title: "手机号",
    dataIndex: "phone",
  },
  {
    title: "诊治类别",
    dataIndex: "threatType",
  },
  {
    title: "医院",
    dataIndex: "hospital",
  },
  {
    title: "operation",
    dataIndex: "operation",
  },
];
const data = ref([])
onMounted(async () => {
  const res = await myAxios({
    method: "get",
    url: "/doctor/list",
  })
  data.value = res.data
  // 这里是给数组加上key=id，key是表格用来区分每条数据的
  data.value.filter((item) => {
    item.key = item.id;
    item.sex = (item.sex === 1) ? "男" : "女";
    // console.log(item,"item")
  })
  // console.log(data.value, "myData")
})

const dataSource = ref(data);
const editableData = reactive({});
// todo 修改
const edit = (key) => {
  editableData[key] = cloneDeep(
      dataSource.value.filter((item) => key === item.key)[0]
  );
  console.log(editableData[key]);
};
//这里是修改数组保存的逻辑 和后端有不匹配的地方在这里修改一下
const save = async (key) => {
  Object.assign(
      dataSource.value.filter((item) => key === item.key)[0],
      editableData[key]
  );
  // 这里发现data 和 dataSource 修改的那条数据都改变了
  const updateDataSource = dataSource.value.filter((item) => key === item.key)[0]
  if (updateDataSource.doctorLevel === "主任医师") {
    updateDataSource.levelId = 1

  } else if (updateDataSource.doctorLevel === "普通医师") {
    updateDataSource.levelId = 2
  } else {//实习医师
    updateDataSource.levelId = 3
  }
  if (updateDataSource.treatType === "肩部") {
    updateDataSource.typeId = 1
  } else if (updateDataSource.treatType === "踝部") {
    updateDataSource.typeId = 2
  } else if (updateDataSource.treatType === "膝部") {
    updateDataSource.typeId = 3
  } else if (updateDataSource.treatType === "腰部") {
    updateDataSource.typeId = 9
  } else if (updateDataSource.treatType === "头部") {
    updateDataSource.typeId = 10
  } else if (updateDataSource.treatType === "肘部") {
    updateDataSource.typeId = 11
  } else {
    updateDataSource.typeId = 12
  }
  const res = await myAxios({
    method: "post",
    url: "/doctor/update",
    data: {
      "id": updateDataSource.id,
      "accountId": updateDataSource.accountId,
      "name": updateDataSource.name,
      "age": updateDataSource.age,
      "sex": updateDataSource.sex === "男" ? 1 : 2,
      "levelId": updateDataSource.levelId,
      "phone": updateDataSource.phone,
      "typeId": updateDataSource.typeId,
      "hospital": updateDataSource.hospital
    }
  })
  console.log(res, "edit save")
  delete editableData[key];
};
const cancel = (key) => {
  delete editableData[key];
};
// todo 删除
const onDelete = (key) => {
  //获取删除医师的id
  let delId;
  let delAccountId;
  const delDoctor = dataSource.value.filter((item) => {
    if (item.key === key) {
      delId = item.id
      delAccountId = item.accountId
    }
  });
  const res = myAxios({
    method: "post",
    url: "/doctor/delete",
    data: {
      "id": delId,
      "accountId": delAccountId
    }
  })
  dataSource.value = dataSource.value.filter((item) => item.key !== key);
  console.log(res, delId, delAccountId)

};
// todo 增加

const modalText = ref('Content of the modal');
const open = ref(false);
const confirmLoading = ref(false);
const showModal = () => {
  open.value = true;
};
// 提交表单
const handleOk = async () => {

  await onFinish()
  confirmLoading.value = true;
  setTimeout(() => {
    open.value = false;
    confirmLoading.value = false;
  }, 2000);
  location.reload();
};

const formState = reactive({
  name: '',
  uname: '',
  pwd: '',
  utype: '',
  age: 0,
  sex: 0,
  levelId: 0,
  phone: '',
  typeId: 0,
  hospital: ''

});
const onFinish = async () => {
  const res =await myAxios({
    method: "post",
    url: "/doctor/add",
    data: formState
  })
  console.log('Success:', formState );


};
const onFinishFailed = errorInfo => {
  console.log('Failed:', errorInfo);
};
</script>
<style scoped>
.editable-row-operations a {
  margin-right: 8px;
}
</style>
